/**
 * 
 */
package com.wistech.search.solr;

import java.io.IOException;
import java.io.StringReader;
import java.net.URLEncoder;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang.StringUtils;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

/**
 * @author Liuye
 * 
 */
@SuppressWarnings("serial")
public class AnalysisServlet extends GenericServlet {
	private String charset = "UTF-8";

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#service(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse)
	 */
	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		String wordParam = req.getParameter("word");
		if (StringUtils.isNotBlank(wordParam)) {
			// 处理userSmart参数
			boolean useSmart = true;
			String useSmartParam = req.getParameter("useSmart");
			if (StringUtils.isNotBlank(useSmartParam)
					&& "false".equals(useSmartParam.toLowerCase())) {
				useSmart = false;
			}
			String terms = analysis(new StringReader(wordParam), useSmart);
			if (StringUtils.isNotBlank(terms)) {
				res.setCharacterEncoding(charset);
				res.getOutputStream().print(URLEncoder.encode(terms, charset));
				res.flushBuffer();
				return;
			}
		}
	}

	public String analysis(StringReader reader, boolean useSmart) {
		IKSegmenter analyzer = new IKSegmenter(reader, useSmart);
		StringBuffer terms = new StringBuffer();
		Lexeme lexeme;
		try {
			lexeme = analyzer.next();
			while (lexeme != null) {
				terms.append(lexeme.getLexemeText()).append(" ");
				lexeme = analyzer.next();
			}
		} catch (IOException e) {
		}
		return StringUtils.trim(terms.toString());
	}
}
